<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use ba\Tree;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 商品分类
 *
 */
class Category extends Backend
{
    /**
     * Category模型对象
     * @var \app\admin\model\Category
     */
    protected $model = null;

    protected $quickSearchField = ['id'];

    protected $defaultSortField = 'id,desc';

    protected $preExcludeFields = ['createtime', 'updatetime'];
    /**
     * @var bool
     */
    private $assembleTree;
    /**
     * @var array|mixed|null
     */
    private $keyword;
    /**
     * @var array|mixed|null
     */
    private $initValue;
    /**
     * @var Tree
     */
    private $tree;

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Category;
        $this->tree = Tree::instance();

        $isTree = $this->request->param('isTree', true);
        $this->initValue = $this->request->get("initValue/a", '');
        $this->keyword = $this->request->request("quick_search");

        $this->assembleTree = $isTree && !$this->keyword && !$this->initValue;
    }

    public function index()
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $this->success('', [
            'list' => $this->getGroups(),
            'remark' => get_route_remark(),
        ]);
    }

    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if (isset($data['id']) && isset($data['category_id']) && $data['id'] == $data['category_id']) {
                    throw new ValidateException('上级分类不能为自己');
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }

    public function getGroups($where = [])
    {
        $pk = $this->model->getPk();
        $initKey = $this->request->get("initKey/s", $pk);

        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
            }
        }

        if ($this->initValue) {
            $where[] = [$initKey, 'in', $this->initValue];
        }

        list($where2, $alias, $limit, $order) = $this->queryBuilder();
        $data = $this->model
            ->alias($alias)
            ->where($where)
            ->where($where2)
            ->select();
        // 获取第一个权限的名称
        foreach ($data as $datum) {
            $datum->cate_name = $this->model->where('id', $datum->category_id)->value('cate', '顶级分类');
        }
        return $this->assembleTree ? $this->tree->assembleChild($data, 'category_id') : $data;
    }

    public function select()
    {
        $data = $this->getGroups([['switch', '=', 1]]);

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'cate'));
        }
        $this->success('', [
            'options' => $data,
        ]);
    }

}